package com.example.shirospring.controller;

import com.example.shirospring.entity.User;
import com.example.shirospring.service.UserService;
import com.example.shirospring.util.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("login")
    public Result login(@RequestBody User user, @RequestParam(defaultValue = "false") boolean rememberMe) {
        // 1.创建subject对象
        Subject subject = SecurityUtils.getSubject();

        // 2.封装请求数据到token
        AuthenticationToken token = new UsernamePasswordToken(user.getName(), user.getPwd(), rememberMe);

        // 3.调用login方法进行登录认证
        try {
            subject.login(token);
            return Result.ok("登录成功");
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("用户不存在");
            return Result.error("登录失败，用户不存在");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            System.out.println("密码错误");
            return Result.error("登录失败，密码错误");
        } catch (AuthenticationException e) {
            e.printStackTrace();
            System.out.println("其余异常");
            return Result.error("登录失败");
        }
    }
}
